package com.activity;

import com.misc.Tool;
import com.type.Topic;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ViewMyCreatedTopicActivity extends ListActivity {
	// constant
	static final String ALWAYS_HIDE_SBCB_BUTTON_AND_NOT_HIDE_CMT_BUTTON = "always_hide_sbcb_button_and_not_hide_cmt_button";
	static final String CREATOR_PH_NUM = "creator_ph_num";
	
	// field
	String myPhNum;
	SimpleAdapter adapter;

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myPhNum = getIntent().getStringExtra(MainActivity.MY_PH_NUM);
		(new FetchMyCreatedTopicTask(this)).execute(MainActivity.SERVER_IP, MainActivity.PORT, myPhNum);
	}

	
	class FetchMyCreatedTopicTask extends AsyncTask<String, Void, ArrayList<Topic>> {
	    ViewMyCreatedTopicActivity viewMyCreatedTopicActivity; 
	
	    public FetchMyCreatedTopicTask(ViewMyCreatedTopicActivity viewMyCreatedTopicActivity) {
	        this.viewMyCreatedTopicActivity = viewMyCreatedTopicActivity;
	    }
	
	    @Override
		protected ArrayList<Topic> doInBackground(String... params) {
	    	ArrayList<Topic> topicList = new ArrayList<Topic>();
	    	Socket socket = null;
	    	DataOutputStream dos = null;	
	    	DataInputStream dis = null;
			try {
				socket = new Socket(params[0], Integer.parseInt(params[1]));
				dos = new DataOutputStream(socket.getOutputStream());
				dis = new DataInputStream(socket.getInputStream());
				dos.writeInt(FrdTopicActivity.FETCH_USER_CREATED_TOPIC);
				
				dos.writeUTF(params[2]);	// my phone number
				int topicCount = dis.readInt();
				if(topicCount > 0) {
					for(int i = 0; i < topicCount; i++) {
						Topic topic = new Topic();
						topic.setTitle(dis.readUTF());
						topic.setContent(dis.readUTF());
						topic.setPhoto(Tool.receiveByteArray(dis));
						topicList.add(topic);
					}
				} 
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					dis.close();
					dos.close();
					socket.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return topicList;
		}
	
	    @Override
	    protected void onPostExecute(ArrayList<Topic> topicList) {
	        if (viewMyCreatedTopicActivity != null) {
	            viewMyCreatedTopicActivity.onFetchMyCreatedTopicTaskComplete(topicList);
	        }
	    }
	}
	
	
	public void onFetchMyCreatedTopicTaskComplete(ArrayList<Topic> topicList) {
		if(topicList.isEmpty())
			Toast.makeText(this, "you haven't created any topic yet", Toast.LENGTH_LONG).show();
		else {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			for (Topic topic : topicList) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("topic_photo", Tool.byteArray2Bitmap(topic.getPhoto()));
				map.put("topic_title", topic.getTitle());
				map.put("topic_content", topic.getContent());
				list.add(map);
			}
			adapter = new SimpleAdapter(this, list, R.layout.user_topic_list_view_item, new String[] { "topic_photo",
					"topic_title", "topic_content" }, new int[] { R.id.ivTopicPhoto, R.id.tvTopicTitle, R.id.tvTopicContent });
			adapter.setViewBinder(new ViewBinder() {
				@Override
				public boolean setViewValue(View view, Object data, String textRepresentation) {
					if ((view instanceof ImageView) && (data instanceof Bitmap)) {
						ImageView iv = (ImageView) view;
						Bitmap bitmap = (Bitmap) data;
						iv.setImageBitmap(bitmap);
						return true;
					} else
						return false;
				}
			});

			getListView().setAdapter(adapter);
			getListView().setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					Intent intent = new Intent(ViewMyCreatedTopicActivity.this, UserTopicDetailActivity.class);
					intent.putExtra(ALWAYS_HIDE_SBCB_BUTTON_AND_NOT_HIDE_CMT_BUTTON, true);
					intent.putExtra(CREATOR_PH_NUM, myPhNum);
					@SuppressWarnings("unchecked")
					Map<String, Object> map = (Map<String, Object>) adapter.getItem(position);
					String title = (String) map.get("topic_title");
					intent.putExtra(FrdTopicActivity.TITLE, title);
					intent.putExtra(MainActivity.MY_PH_NUM, myPhNum);
					intent.putExtra(MainActivity.MY_NAME, getIntent().getStringExtra(MainActivity.MY_NAME));
					intent.putExtra(MainActivity.MY_AVATAR, getIntent().getParcelableExtra(MainActivity.MY_AVATAR));
					startActivity(intent);
				}
			});
		}
	}
}